<template>
  <div class="biz-container">
    <table-layout
      :haveSider="false"
      :isSearch="true"
    >
      <template #headCustom>

      </template>
      <template #searchBox>
        <search-layout
          :formInfos="q_formInfos"
          :formDatas="q_formDatas"
          message=""
          @onFind="onFind"
          @onChangeType="onChangeType"
        ></search-layout>
      </template>
      <template #batchOperat>
        <batch-operat-btn
          :addData="false"
          @onAddData="onAddData"
          :delectData="false"
          @onDelectData="onDelectData"
          :optData="optText"
          @onOptData="onBatchAudit"
        >
        </batch-operat-btn>
      </template>
      <template #tableList="slotData">
        <a-list-table
          :columns="columns"
          :tableData="listdata"
          :pagination="pagination"
          :isSelecttion="true"
          :loading="loading"
          :scroll="{y:slotData.tableHeight}"
          @onTableChange="handleTableChange"
          @onselectChange="onselectChange"
          @onAction="onAction"
          :links="links"
          @onTouchlinkCell="onTouchlinkCell"
        >
        </a-list-table>
      </template>
    </table-layout>
    <!-- <viewModal ref="viewModal" @ok="handleModalSaveOk" @close="handleModalCancel" /> -->

  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
// import viewModal from './viewModal' 
import exportExcel from '@/views/app/biz/common/exportExcel/index.vue'
import {
  getStoreByConditions,
  getStoreByConditionsCount,
} from './salegoods'


// 字段列表
const columns = [
  { title: '客户单位代码', dataIndex: 'keHushxxdm', key: 'keHushxxdm', align: 'center' },
  { title: '客户单位名称', dataIndex: 'keHumc', key: 'keHumc', align: 'center' },
  // { title:'上级代码', dataIndex:'parentDm', key: 'parentDm', align: 'center'},
  // { title: '状态', dataIndex: 'state', key: 'state', align: 'center' },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'operation',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'action' },
  },
]
let links = ['areaDm']

export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    // viewModal,
    exportExcel,
  },
  data () {
    return {
      columns: columns,
      listdata: [],
      links: links,
      loading: false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '10', '50', '100'],
      },
      // 查询表单
      q_formInfos: [
        // { label: '数据有效范围名称', name: 'areaCT', type: 'input', placeholder: '数据有效范围名称' },
        // { label: [ '刷新'], type: 'botton' }
      ],
      // 查询表单绑定数据
      q_formDatas: {
        customerPid: null,
        pid: null,
        supplierOrgPid: null,
        invoiceType: null
      },
      pData: {}, // 条件查询参数
      isJump: false,
      optText: '',
      selectedRowKeys: [],
      selectedRows: [],
      notAudit: false,
      side: null
    }
  },
  computed: {},
  watch: {
    $route: {
      handler: function (val, oldVal) {
        console.log(this.$route.name);
        console.log(this.$route.meta);
        //判断是进入该页面还是离开
        if (this.$route.name == 'saleGoodsStore') {
          //读取该页面是否缓存，未缓存时：
          if (!this.$route.meta.keepAlive) {
            //读取页面跳转传参
            if (this.$route.params.keHuPid) {
              this.q_formDatas.keHuPid = this.$route.params.keHuPid
            }
            this.getTotal()
            this.getList(this.q_formDatas)
          } else {
            console.log(this.$route.params.isBack);
            //已缓存时判断是否是返回
            if (!this.$route.params.isBack) {
              this.getTotal()
              this.getList(this.q_formDatas)
            }
            this.isJump = false
          }
        }
      },
      deep: true,
      immediate: true
    }
  },
  beforeRouteEnter (to, from, next) {
    // console.log('beforeRouteEnter',to,from);
    next(vm => {
      console.log(vm.isJump);
    });
  },
  beforeRouteLeave (to, from, next) {
    if (this.isJump) {
      from.meta.keepAlive = true
    } else {
      from.meta.keepAlive = false
    }
    next();
  },
  mounted () {
    console.log('mounted');
    this.getTotal()
    this.getList(this.q_formDatas)

  },
  methods: {
    // 初始化页面时得到总数
    async getTotal () {
      let pages = ''
      pages = await getStoreByConditionsCount(this.q_formDatas)
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal = (showTotal) => { return `共 ${showTotal} 条` }
      }
    },
    // 初始化查询时的数据列表
    async getList (params) {
      console.log('请求列表时传入的数据', params)
      let actionBtn = ['进入']
      this.loading = true
      let listdata = []
      let res = ''
      res = await getStoreByConditions(params, this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
        for (let item of resdata) {
          listdata.push({
            key: item.pid,
            standardCode: item.keHushxxdm,
            action: actionBtn,
            ...item
          }
          )
        }
        this.listdata = listdata
      } else {
        this.listdata = []
      }
      console.log(this.listdata)
    },
    // 新增按钮 点击了新增
    onAddData () {
      this.$refs.addModal.addModal()
    },
    // 关闭模态详细框
    handleModalCancel () {
    },
    // 模态详细框提交按钮
    handleModalSaveOk () {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction (text, record, index) {
      if (text == '进入') {
        this.isJump = true
        this.$router.push({
          name: 'saleGoodsMatch',
          params: {
            isJump: this.isJump,
            pathName: this.$route.name,
            areaDm: record.keHushxxdm
          }
        })
        // this.showConfirm(record)
      }
    },

    // 触发改变页码,筛选,排序时的回调
    handleTableChange (pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    //下载商品数据
    onDownloadStore () {
      //   this.$refs.areaModal.showModal(null,null)
    },
    //下载空模板
    onDownloadDemo () {
      //x下载模板，如需请求数据，则在此请求数据后执行以下
      let listName = "基础商品信息"
      let listHeader = ['商品自编码', '商品名称', '一级分类（学科、品类）', '二级分类（用途、品目）', '三级分类（部位、功能、品种）', '品牌']
      let listField = ['code', 'productNameZh', 'first', 'second', 'third', 'brand']
      let exportList = []
      this.$refs.export.setData(listName, listHeader, listField, exportList)
    },
    // 搜索栏选择下拉select触发搜索val[0]表示选中的record中的pid,val[1]表示选中的record全部信息
    onChangeType (name, val) {
      console.log('formName', name)
      console.log('val', val)
      switch (name) {
        case 'pid':
          if (!val[0]) {
            this.q_formDatas.pid = null
          }
          this.onFind()
          break
        case 'supplierOrgPid':
          if (!val) {
            this.q_formDatas.supplierOrgPid = null
          }
          this.onFind()
          break
        case 'customerPid':
          if (!val) {
            this.q_formDatas.customerPid = null
          }
          this.onFind()
          break
        case 'invoiceType':
          if (!val) {
            this.q_formDatas.invoiceType = null
          }
          this.onFind()
          break
      }
    },
    // 查询按钮
    onFind () {
      this.pagination.current = 1
      this.getTotal()
      this.getList(this.q_formDatas)
    },

    onTouchlinkCell (text, record, index, link) {
      console.log(record);
      if (link == 'areaDm') {
        this.$refs.viewModal.showModal(record.pid)
      }
    },
    // 多选批量操作
    onselectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.zhuangTai != '待审核') {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },
    onDelectData () {
      if (this.selectedRows.length) {
        this.showDelConfirm(this.selectedRows)
      } else {
        this.$message.warning({ content: '未选择要删除的记录', duration: 3 })
      }
    },
    showDelConfirm (val, type) {
      let datas = []
      if (type == '1') {
        datas[0] = val
      } else {
        datas = val
      }
      const that = this;
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk () {
          let reqArr = []
          let key = 'self'
          for (const item of datas) {
            reqArr.push(that.delOrder(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1' && item.data) {
                that.$message.success({ content: '记录删除成功', duration: 3 })
              } else {
                that.$message.error({ content: '记录删除失败，原因：' + item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content: '操作出错:' + err, duration: 3 })
          })
        },
        onCancel () { },
      });
    },
    async delOrder (val) {
      let res = await deleteInfo(val)
      return res
    },
    onBatchAudit () {
      if (this.selectedRows.length) {
        if (this.notAudit) {
          this.$message.warning({ content: '已选项中含有已审核的记录，请选择待审核的记录', duration: 3 })
        } else {
          this.$refs.auditModal.batchModal(this.selectedRows)
        }
      } else {
        this.$message.warning({ content: '未选择要审核的记录', duration: 3 })
      }
    }
  },
}
</script>

<style>
.importTip {
  line-height: 40px;
  font-size: 14px;
  color: #fab600;
}
</style>